<template>
  <div>
    <el-dialog
      :visible="addDialog"
      width="50%"
      :before-close="closeDialog"
      top="5vh"
      :close-on-click-modal="false"
    >
      <div class="dialogTitle" slot="title">
        {{ this.form.id ? "编辑文件" : "新增文件" }}
      </div>
      <el-form :model="form" label-width="180px">
        <el-form-item label="文件名称:">
          <el-input
            v-model="form.fileName"
            autocomplete="off"
            placeholder="请输入"
          />
        </el-form-item>

        <el-form-item label="发布单位:">
          <el-select v-model="form.fileCompany" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="可查看单位:">
          <el-select
            multiple
            v-model="form.fileView"
            placeholder="请选择"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注:">
          <el-input
            v-model="form.remark"
            autocomplete="off"
            placeholder="请输入 "
          />
        </el-form-item>
        <el-form-item label="文件:">
          <el-upload
            action=""
            :http-request="UploadImage3"
            :file-list.sync="fileList"
            :limit="3"
            list-type="picture-card"
            :on-exceed="handleExceed"
            :on-change="handleFileChange"
            :on-remove="handleRemove"
          >
            <i v-if="fileList.length < 3" slot="default" class="el-icon-plus" />
            <div slot="file" slot-scope="{ file }">
              <img
                class="el-upload-list__item-thumbnail"
                src="@/assets/common/filePic.jpeg"
                alt=""
              />
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <i class="el-icon-delete" />
                </span>
              </span>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!form.id" class="addBtn" type="primary" @click="submit"
          >确定新增</el-button
        >
        <el-button v-else class="addBtn" type="primary" @click="submit"
          >确定修改</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fileAdd, fileUpdate } from "@/api/fileUpload";
import { departmentList } from "@/api/systemManagement";
import { uploadApi } from "@/api/login";
import { getUserInfo } from "@/utils/auth";
export default {
  name: "addFile",
  props: {
    addDialog: {
      type: Boolean,
      default: false,
    },
    dialogId: {
      type: String,
      default: null,
    },
  },
  components: {},
  data() {
    return {
      form: {
        fileName: "",
        fileCompany: "",
        fileView: "",
        remark: "",
      },
      options: [],
      fileList: [],
      uploaderSubmit: [],
    };
  },
  created() {
    this.departmentListApi();
  },
  methods: {
    async submit() {
      this.openLoading();
      if (this.form.id) {
        const res = await fileUpdate({
          id: this.form.id,
          createdBy: JSON.parse(getUserInfo()).userId,
          fileName: this.form.fileName,
          fileCompany: this.form.fileCompany,
          fileView: this.form.fileView.toString(),
          remark: this.form.remark,
          filePath: this.uploaderSubmit.map((item) => {
            return {
              filePath: item.filePath,
              fileName: item.fileName,
            };
          }),
        });

        if (res.code == 0) {
          this.$message.success("修改成功");
          this.closeDialog();
          this.$parent.firePage();
        } else {
          this.$message.error("新增失败");
        }
      } else {
        const res = await fileAdd({
          createdBy: JSON.parse(getUserInfo()).userId,
          fileName: this.form.fileName,
          fileCompany: this.form.fileCompany,
          fileView: this.form.fileView.toString(),
          remark: this.form.remark,
          filePath: this.uploaderSubmit.map((item) => {
            return {
              filePath: item.filePath,
              fileName: item.fileName,
            };
          }),
        });

        if (res.code == 0) {
          this.$message.success("新增成功");
          this.closeDialog();
          this.$parent.firePage();
        } else {
          this.$message.error("新增失败");
        }
      }
      this.openLoading().close();
    },
    closeDialog() {
      this.form = {
        fileName: "",
        fileCompany: "",
        fileView: "",
        remark: "",
      };
      this.fileList = [];
      this.uploaderSubmit = [];

      this.$emit("update:addDialog", false); // 触发父组件更新
    },
    async departmentListApi() {
      const res = await departmentList();
      this.options = this.flattenDepartments(res.data);
    },
    flattenDepartments(data, result = []) {
      data.forEach((department) => {
        const { departmentVoList, ...dept } = department;
        result.push(dept); // 添加当前节点[3,5](@ref)

        if (departmentVoList?.length) {
          this.flattenDepartments(departmentVoList, result); // 递归处理子节点[4](@ref)
        }
      });
      return result;
    },
    async UploadImage3(file) {
      this.openLoading();
      const formData = new FormData();
      formData.append("file", file.file);

      const res = await uploadApi(formData);
      if (res.code === 0) {
        this.uploaderSubmit.push({
          filePath: res.data,
          fileName: file.file.name,
        });
      } else {
        this.fileList.pop();
      }
      this.openLoading().close();
    },
    handleExceed() {
      this.$message.warning("最多上传 3 个文件");
    },
    handleFileChange(file, fileList) {
      this.fileList = fileList; // 手动同步
    },
    handleRemove(e) {
      this.uploaderSubmit = this.uploaderSubmit.filter((item) => {
        return item.uid !== e.uid;
      });
      this.fileList = this.fileList.filter((item) => {
        return item.uid !== e.uid;
      });
    },
  },
  mounted() {},
  watch: {},
  computed: {},
  filters: {},
};
</script>

<style scoped lang="scss">
.dialogTitle {
  position: relative;
  padding-left: 10px; /* 调整文本与颜色条之间的间距 */
  font-weight: bold;
}
.dialogTitle::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  border-radius: 2px;
  transform: translateY(-50%);
  width: 4px; /* 颜色条的宽度 */
  height: 14px; /* 颜色条的高度 */
  background-color: #249451; /* 颜色条的颜色 */
}
.el-select {
  width: 100%;
}
::v-deep .el-dialog__body {
  padding-right: 50px !important;
}
::v-deep .dialog-footer {
  text-align: center;
  .addBtn {
    background: #249451;
    border-radius: 4px 4px 4px 4px;
    border: none;
    color: #fff;
  }
}

::v-deep .el-upload--picture-card {
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
::v-deep .el-upload-list--picture-card .el-upload-list__item-actions {
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
::v-deep .el-upload-list--picture-card .el-upload-list__item {
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
</style>
